/**
 * 日志记录工具类
 */

import { config } from './config.js';

class LogManager {
  // 用于存储各操作的行为次数
  static actionCounters = new Map();

  /**
   * 记录用户操作日志
   * @param {string} action - 操作行为
   * @param {number} frequency - 操作频次（用于向后兼容，实际频次通过累积计算）
   * @param {Object} extraData - 其他额外数据
   */
  static async logAction(action, frequency = 1, extraData = {}) {
    try {
      // 获取或初始化该操作的计数器
      let count = this.actionCounters.get(action) || 0;
      count += 1;
      this.actionCounters.set(action, count);

      // 构造日志数据
      const logData = {
        action,
        frequency: count, // 使用累积的操作次数作为频次
        terminal: navigator.userAgent,
        timestamp: new Date().toISOString(),
        url: window.location.href,
        extraData
      };

      // 发送日志到后端
      const response = await fetch(`${config.domain}/log`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(logData)
      });

      const result = await response.json();
      
      if (!result.success) {
        console.error('Failed to log action:', result.message);
      }
      
      return result;
    } catch (error) {
      console.error('Error logging action:', error);
      return { success: false, error: error.message };
    }
  }

  /**
   * 获取所有日志数据
   */
  static async getAllLogs() {
    try {
      const response = await fetch(`${config.domain}/logs`);
      const result = await response.json();
      
      if (!result.success) {
        console.error('Failed to fetch logs:', result.message);
        return [];
      }
      
      return result.data;
    } catch (error) {
      console.error('Error fetching logs:', error);
      return [];
    }
  }

}

export default LogManager;